package com.inno.auth.domain.strategy;

import cn.hutool.core.util.IdUtil;
import com.inno.auth.common.enums.IsDeletedFlagEnum;
import com.inno.auth.common.enums.LoginTypeEnum;
import com.inno.auth.common.enums.YesOrNoEnum;
import com.inno.auth.common.error.AuthException;
import com.inno.auth.common.utils.DateUtils;
import com.inno.auth.domain.utils.WechatUtil;
import com.inno.auth.infra.basic.entity.PlannerUsers;
import com.inno.auth.infra.basic.service.PlannerUsersService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * 微信登录
 * @author sean
 */
@Component
public class WechatLoginHandler implements LoginHandler{
    @Resource
    private PlannerUsersService plannerUsersService;
    @Resource
    private WechatUtil wechatUtil;

    private final Object LOCK = new Object();

    @Override
    public LoginTypeEnum getType() {
        return LoginTypeEnum.LOGIN_TYPE_WECHAT;
    }

    @Override
    public PlannerUsers login(PlannerUsers users) {
        String openId = wechatUtil.getOpenId(users.getWechatCode());
        if (StringUtils.isBlank(openId)){
            throw new AuthException("登录失败");
        }

        synchronized (LOCK){
            PlannerUsers byUsername = plannerUsersService.queryByUsername(users);
            if (Objects.nonNull(byUsername)){
                throw new AuthException("当前用户名已被占用 请更换!");
            }
            PlannerUsers byOpenId = plannerUsersService.queryByOpenId(openId);
            if (Objects.isNull(byOpenId)){
                // 新用户 注册
                byOpenId = new PlannerUsers();
                byOpenId.setOpenid(openId);
                long snowflakeNextId = IdUtil.getSnowflakeNextId();
                byOpenId.setId(snowflakeNextId);
//            byOpenId.setUsername("用户" + openId.substring(0,3) + String.valueOf(snowflakeNextId).substring(0, 2));
                Date nowDate = DateUtils.getNowDate();
                byOpenId.setCreateTime(nowDate);
                byOpenId.setRegisterTime(nowDate);
                byOpenId.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode().toString());
                byOpenId.setUsername(users.getUsername());
                byOpenId.setAvatar(users.getAvatar());
                byOpenId.setGender(YesOrNoEnum.YES.getCode());
                plannerUsersService.insert(byOpenId);
            }else {
                if (YesOrNoEnum.YES.getCode().equals(byOpenId.getIsDeleted())){
                    throw AuthException.of("账号可能已注销/禁用");
                }
            }
            return byOpenId;
        }
    }

}
